package com.cabal.config;

import com.cabal.common.constants.SystemConstants;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


@Configuration
@Order(1)
public class DataSourceConfig {

    @Bean(SystemConstants.DS_KEY_ACCOUNT_CONFIG)
    @ConfigurationProperties(prefix = "spring.datasource.account")
    public HikariConfig accountHikariConfig() {
        return new HikariConfig();
    }

    @Bean(SystemConstants.DS_KEY_CABALCASH_CONFIG)
    @ConfigurationProperties(prefix = "spring.datasource.cabalcash")
    public HikariConfig cabalCashHikariConfig() {
        return new HikariConfig();
    }

    @Bean(SystemConstants.DS_KEY_SERVER01_CONFIG)
    @ConfigurationProperties(prefix = "spring.datasource.server01")
    public HikariConfig server01HikariConfig() {
        return new HikariConfig();
    }

    @Bean(SystemConstants.DS_KEY_CABALMALL_CONFIG)
    @ConfigurationProperties(prefix = "spring.datasource.cabalmall")
    public HikariConfig cabalMallHikariConfig() {
        return new HikariConfig();
    }

    @Bean(SystemConstants.DS_KEY_ACCOUNT)
    public DataSource accountDataSource() {
        return new HikariDataSource(accountHikariConfig());
    }

    @Bean(SystemConstants.DS_KEY_CABALCASH)
    public DataSource cabalCashDataSource() {
        return new HikariDataSource(cabalCashHikariConfig());
    }

    @Bean(SystemConstants.DS_KEY_SERVER01)
    public DataSource server01DataSource() {
        return new HikariDataSource(server01HikariConfig());
    }

    @Bean(SystemConstants.DS_KEY_CABALMALL)
    public DataSource cabalMallDataSource() {
        return new HikariDataSource(cabalMallHikariConfig());
    }


    @Bean
    @Primary
    public DataSource dynamicDataSource() {
        Map<Object, Object> dataSourceMap = new HashMap<>(10);
        dataSourceMap.put(SystemConstants.DS_KEY_ACCOUNT, accountDataSource());
        dataSourceMap.put(SystemConstants.DS_KEY_CABALCASH, cabalCashDataSource());
        dataSourceMap.put(SystemConstants.DS_KEY_SERVER01, server01DataSource());
        dataSourceMap.put(SystemConstants.DS_KEY_CABALMALL, cabalMallDataSource());

        //设置动态数据源
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        dynamicDataSource.setDefaultTargetDataSource(accountDataSource());
        return dynamicDataSource;
    }

}
